package com.efounder.zone.commentview;

import android.content.Context;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.efounder.chat.activity.ViewPagerActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.zone.R;
import com.efounder.zone.widget.CircleMovementMethod;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;

/**
 * 评论列表的adapter
 * Created by slp on 2018/5/9.
 */
public class CommentListAdapter extends RecyclerView.Adapter<CommentListAdapter.CommentViewHolder> implements BGANinePhotoLayout.Delegate {

    private List<ZoneCommentBean> mCommentBeanList;
    private Context mContext;
    private WeChatDBManager mWeChatDBManager;
    private onCommentListener listener;

    public CommentListAdapter(List<ZoneCommentBean> commentBeanList, Context context, onCommentListener listener) {
        this.mCommentBeanList = commentBeanList;
        this.mContext = context;
        this.mWeChatDBManager = WeChatDBManager.getInstance();
        this.listener = listener;
    }

    @Override
    public CommentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.mobile_zone_item_comment, parent, false);
        return new CommentViewHolder(view);
    }

    @Override
    public void onBindViewHolder(CommentViewHolder holder, int position) {
        ZoneCommentBean zoneCommentBean = mCommentBeanList.get(position);
        String content = zoneCommentBean.getContent();

        //判断content中是否为json数据结构
        try {
            JSONObject jsonObject = new JSONObject(content);

            if (jsonObject.has("text")) {
                String commentText = jsonObject.getString("text");

                setCommentText(zoneCommentBean, holder.tvCommentDetail, commentText);
            }
            if (jsonObject.has("images")) {
                JSONArray jsonArray = jsonObject.getJSONArray("images");
                ArrayList<String> imgList = new ArrayList<>();
                for (int i = 0; i < jsonArray.length(); i++) {
                    imgList.add(jsonArray.getString(i));
                }
                if (imgList.size() <= 0) {
                    holder.bplCommentDetailPhoto.setVisibility(View.GONE);
                } else {
                    holder.bplCommentDetailPhoto.setVisibility(View.VISIBLE);
                    holder.bplCommentDetailPhoto.setData(imgList);
                    holder.bplCommentDetailPhoto.setDelegate(CommentListAdapter.this);
                }
            }

        } catch (Exception e) {
            holder.bplCommentDetailPhoto.setVisibility(View.GONE);
            String commentText = content;
            setCommentText(zoneCommentBean, holder.tvCommentDetail, commentText);
        }
    }

    /**
     * 设置显示的内容
     *
     * @param commentBean
     * @param tv
     * @param commentText
     */
    private void setCommentText(final ZoneCommentBean commentBean, TextView tv, String commentText) {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        String commentUserId = String.valueOf(commentBean.getCommentUserId());

        String nickName = null;
        if (commentBean.getCommentUserNickname() != null && !"".equals(commentBean.getCommentUserNickname())) {
            nickName = (String) commentBean.getCommentUserNickname();
        } else {
            User commentUser = mWeChatDBManager.getOneUserById(commentBean.getCommentUserId());
            nickName = commentUser.getNickName();
        }
        if (commentBean.getReplyUserId() == null) {
            builder.append(setClickableSpan(nickName, commentUserId));
        } else {
            int replyId = (int) commentBean.getReplyUserId();
            String replyUserId = String.valueOf(replyId);
            // User replyUser = mWeChatDBManager.getOneUserById(replyId);

            builder.append(setClickableSpan(nickName, commentUserId));
            builder.append(ResStringUtil.getString(R.string.zone_reply));
            //回复人姓名
            String replayName = null;
            if (commentBean.getReplyUserNickname() != null && !"".equals(commentBean.getReplyUserNickname())) {
                replayName = (String) commentBean.getReplyUserNickname();
            } else {
                User user = mWeChatDBManager.getOneUserById(replyId);
                replayName = user.getNickName();
            }

            builder.append(setClickableSpan(replayName, replyUserId));
        }
        builder.append(" : ");
        builder.append(setClickableSpanContent(commentText, commentBean));
        builder.append(" ");
        tv.setText(builder);
        // 设置点击背景色
        tv.setHighlightColor(mContext.getResources().getColor(android.R.color.transparent));
//        tv.setHighlightColor(0xff000000);
        final CircleMovementMethod method = new CircleMovementMethod(0x00000000, 0x00000000);
        tv.setMovementMethod(method);

//        tv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if(listener != null){
//                    listener.onCommentClick(commentBean);
//                }
//            }
//        });
    }


    @Override
    public int getItemCount() {
        return mCommentBeanList.size();
    }

    /**
     * 设置评论名字的点击事件
     *
     * @param item
     * @param userId
     * @return
     */
    public SpannableString setClickableSpan(final String item, final String userId) {
        final SpannableString string = new SpannableString(item);
        ClickableSpan span = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
//                Toast.makeText(mContext, userId, Toast.LENGTH_SHORT).show();
                if (listener != null) {
                    listener.onUserClick(userId);
                }
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                // 设置显示的用户名文本颜色
//                ds.setColor(mContext.getResources().getColor(R.color.mobile_zone_like_comment_people_textcolor));
                ds.setColor(JfResourceUtil.getSkinColor(R.color.mobile_zone_like_comment_people_textcolor));
                ds.setUnderlineText(false);
            }
        };

        string.setSpan(span, 0, string.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return string;
    }

    /**
     * 设置评论内容的点击事件
     *
     * @param item
     * @param commentBean
     * @return
     */
    public SpannableString setClickableSpanContent(final String item, final ZoneCommentBean commentBean) {
        final SpannableString string = new SpannableString(item);
        ClickableSpan span = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
//                Toast.makeText(mContext, " content: " + item, Toast.LENGTH_SHORT).show();
                if (listener != null) {
                    listener.onCommentClick(commentBean);
                }
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                // 设置显示的内容文本颜色
//                ds.setColor(mContext.getResources().getColor(R.color.black_text_color));
                ds.setColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
                ds.setUnderlineText(false);
            }
        };
        string.setSpan(span, 0, string.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return string;
    }

    public class CommentViewHolder extends RecyclerView.ViewHolder {

        private TextView tvCommentDetail;
        private BGANinePhotoLayout bplCommentDetailPhoto;

        public CommentViewHolder(View itemView) {
            super(itemView);
            this.tvCommentDetail = (TextView) itemView.findViewById(R.id.tv_comment_detail);
            this.bplCommentDetailPhoto = (BGANinePhotoLayout) itemView.findViewById(R.id.bpl_comment_detail_photo);
        }
    }


    @Override
    public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {

        String[] strings = models.toArray(new String[0]);
        ViewPagerActivity.showImageWall(mContext, strings, position, view);
    }

    public interface onCommentListener {

        /**
         * 点击评论人的名字
         *
         * @param userId 评论人的id
         */
        void onUserClick(String userId);

        /**
         * 点击评论的内容
         *
         * @param zoneCommentBean 评论的bean
         */
        void onCommentClick(ZoneCommentBean zoneCommentBean);
    }
}
